import java.util.Arrays;
import java.util.HashMap;

/**
 * @author VernHe
 * @date 2021年06月14日 11:15
 */
public class Solution_0169 {
    public int majorityElement(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        HashMap<Integer, Integer> map = new HashMap();
        for (int num : nums) {
            if (map.containsKey(num)) {
                Integer times = map.get(num);
                if (times == nums.length >> 1) {
                    return num;
                }
                map.put(num,times + 1);
            } else {
                map.put(num, 1);
            }
        }
        return -1;
    }

    public int majorityElement1(int[] nums) {
        Arrays.sort(nums);
        for (int num : nums) {
            System.out.printf(num + " ");
        }
        System.out.println();
        int half = nums.length >> 1;
        int begin = 0;
        int end = 0;
        int maxTimes = 0;
        int curTimes = 0;
        while (end < nums.length) {
            if (nums[end] == nums[begin]) {
                System.out.println("begin: " + begin + "， end: " + end + "相等");
                curTimes++;
                end++;
            } else {
                System.out.println("begin: " + begin + "， end: " + end + "不相等" + " ,curTimes：" + curTimes);
                if (curTimes > half) {
                    return nums[begin];
                }
                begin = end;
                curTimes = 0;
            }
        }
        if (curTimes > half) {
            return nums[begin];
        }
        return -1;
    }

    /**
     * 题解：必定出现在1/2处
     * @param nums
     * @return
     */
    public int majorityElement2(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length >> 1];
    }
}
